package com.kbt.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.*;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.system.email.Email;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.onekeyshare.OnekeyShare;
import com.kbt.onekeyshare.ShareContentCustomizeCallback;
import com.kbt.util.tool.contact;
import com.kbt.util.utils.ImageManager;
import com.kbt.util.utils.SharePreferenceUtils;

import java.io.*;
import java.util.Date;

/**
 * @Title: KBT_ANDRIOD
 * @Copyright: KJ Co., Ltd. Copyright 2015-2020,  All rights reserved
 * @Description: ${todo}<请描述此文件是做什么的>
 * @author: zhgk
 * @data: 2015/8/18 11:36
 * @version: V1.0
 */
public class ShareToFriendActivity extends Activity {

//    DomobInterstitialAd mInterstitialAd;
    Bitmap bmp=null;
    private  ImageView imageView5;
    private SharePreferenceUtils share;
    private String code;
    private TextView textView55;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.share_for_friend);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.return_share_title);
//        showad();
        //初始化ImageLoader
        ImageManager.init();
        //设置返回按钮事件,关闭当前Activity，返回数据
        ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
        returnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //不创建地址
                setResult(RESULT_CANCELED, null);
                BaseApplication.getInstance().removeActivity(ShareToFriendActivity.this);
                finish();
            }
        });
        BaseApplication.getInstance().addActivity(ShareToFriendActivity.this);
        share = new SharePreferenceUtils(ShareToFriendActivity.this);
        code = share.getString("user_key","");
        imageView5 = (ImageView) findViewById(R.id.imageView5);
        textView55 = (TextView) findViewById(R.id.textView55);
        String message ="点击右上角邀请小伙伴\n\n<font color=\"#FF3300\">1.小伙伴使用您的邀请码绑定提现账户即送您1000积分\n2.使用邀请码绑定提现账户的小伙伴奖励2000积分\n3.所有使用您邀请码的用户均视为您的推广用户，他们在豆花网消费额的10%将返现到您的提现账户</font>";
        textView55.setText(Html.fromHtml(message.replace("\n", "<br />")));
        ImageManager.imageLoader.displayImage(Constants.ServiceInterFace.ServerURL+"static/res/img/dhw.png", imageView5, ImageManager.getOptions(
                R.drawable.loadings, R.drawable.loadings));
        //生成二维码的数据
//        String content="http://m.kua-jie.com/static/shareapp.html";
//        try {
//            bmp=createBitmap(Create2DCode(content));
//        } catch (WriterException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        imageView5.setImageBitmap(bmp);
//
//        ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
//
//        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos1);
//
//        try {
//            Writetemp(baos1.toByteArray());
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//        //保存二位码图片
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
//        if (mInterstitialAd.isInterstitialAdReady()){
//            mInterstitialAd.showInterstitialAd(ShareToFriendActivity.this);
//        } else {
//            Log.i("DomobSDKDemo", "Interstitial Ad is not ready");
//            mInterstitialAd.loadInterstitialAd();
//        }
//        try {
//            Write(baos.toByteArray());
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }


        //设置返回按钮事件,关闭当前Activity，返回数据
        ImageView shareImg = (ImageView) findViewById(R.id.shareImgBtn);
        shareImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开分享链接
                showShare();
            }
        });

        TextView appTitleView = (TextView) findViewById(R.id.center_title);
        appTitleView.setText("邀请小伙伴");
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        oks.setNotification(R.drawable.ic_lancher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(getString(R.string.firendTitle) + code + ")");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://a.app.qq.com/o/simple.jsp?pkgname=com.kbt.activity");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("一个带有检测报告的食品特卖平台,使用邀请码可获2000积分(20元)");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/mnt/sdcard/zibuyu/erweima.png");//确保SDcard下面存在此张图片
        oks.setImageUrl(Constants.ServiceInterFace.ServerURL + "static/res/img/dhw.png");
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://a.app.qq.com/o/simple.jsp?pkgname=com.kbt.activity");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("快来评论吧!");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://a.app.qq.com/o/simple.jsp?pkgname=com.kbt.activity");
        // 是否直接分享（true则直接分享）
        oks.setSilent(true);

        // 启动分享GUI
        oks.show(ShareToFriendActivity.this);

    }


//    public void showad()
//    {
//        mInterstitialAd = new DomobInterstitialAd(this,contact.PUBLISHER_ID,
//                contact.InterstitialPPID, DomobInterstitialAd.INTERSITIAL_SIZE_300X250);
//        mInterstitialAd.setInterstitialAdListener(new DomobInterstitialAdListener() {
//            public void onInterstitialAdReady() {
//                Log.i("DomobSDKDemo", "onAdReady");
//            }
//
//            public void onLandingPageOpen() {
//                Log.i("DomobSDKDemo", "onLandingPageOpen");
//            }
//
//            public void onLandingPageClose() {
//                Log.i("DomobSDKDemo", "onLandingPageClose");
//            }
//
//            public void onInterstitialAdPresent() {
//                Log.i("DomobSDKDemo", "onInterstitialAdPresent");
//            }
//
//            public void onInterstitialAdDismiss() {
//                // Request new ad when the previous interstitial ad was closed.
//                mInterstitialAd.loadInterstitialAd();
//                Log.i("DomobSDKDemo", "onInterstitialAdDismiss");
//            }
//
//            public void onInterstitialAdFailed(DomobAdManager.ErrorCode arg0) {
//                Log.i("DomobSDKDemo", "onInterstitialAdFailed");
//            }
//
//            public void onInterstitialAdLeaveApplication() {
//                Log.i("DomobSDKDemo", "onInterstitialAdLeaveApplication");
//
//            }
//        });
//        mInterstitialAd.loadInterstitialAd();
//
//    }

    public Bitmap Create2DCode(String str) throws WriterException, UnsupportedEncodingException {
        //生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        BitMatrix matrix = new MultiFormatWriter().encode(new String(str.getBytes("GBK"),"ISO-8859-1"), BarcodeFormat.QR_CODE, 300, 300);

        int width = matrix.getWidth();
        int height = matrix.getHeight();
        //二维矩阵转为一维像素数组,也就是一直横着排了
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if(matrix.get(x, y)){
                    pixels[y * width + x] = 0xff000000;
                }

            }
        }
        int[] colors={R.color.WHITE};
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //通过像素数组生成bitmap,具体参考api
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
    public  void Write(byte []b) throws IOException
    {
        File cacheFile =null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File sdCardDir = Environment.getExternalStorageDirectory();
//            long time= Calendar.getInstance().getTimeInMillis();
            String fileName ="erweima.png";
            File dir = new File(sdCardDir.getCanonicalPath()
                    +"/zibuyu/");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            cacheFile = new File(dir, fileName);

        }
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(cacheFile));

            bos.write(b,0,b.length);
            bos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public  void Writetemp(byte []b) throws IOException
    {
        File cacheFile =null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File sdCardDir = Environment.getExternalStorageDirectory();
            Date curDate    =   new    Date(System.currentTimeMillis());//获取当前时间
            String fileName ="temp.jpg";
            File dir = new File(sdCardDir.getCanonicalPath()
                    +"/zibuyu/temp");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            cacheFile = new File(dir, fileName);

        }
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(cacheFile));

            bos.write(b,0,b.length);
            bos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private Bitmap createBitmap( Bitmap src)

    {

        if( src == null )
        {
            return null;
        }
        Paint paint=new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);

        int w = 300;
        int h = 300;
        Bitmap newb = Bitmap.createBitmap( w, h, Bitmap.Config.ARGB_8888 );
        Canvas cv = new Canvas( newb );

        cv.drawColor(Color.WHITE);

        cv.drawBitmap(src, 0, 0, null );
        cv.save( Canvas.ALL_SAVE_FLAG );
        cv.restore();//存储
        return newb;
    }


}
